package com.wnxy.sk.product.controller;


import com.wnxy.sk.common.exception.BusinessException;
import com.wnxy.sk.common.result.Result;
import com.wnxy.sk.common.result.enums.impl.ResultCode;
import com.wnxy.sk.product.constant.PromotionStatus;
import com.wnxy.sk.product.dto.OrderPayDto;
import com.wnxy.sk.product.entity.PromotionSeckill;
import com.wnxy.sk.product.service.IPromotionSeckillService;
import com.wnxy.sk.product.vo.PaymentVo;
import com.wnxy.sk.product.vo.PromotionOrderVo;
import com.wnxy.sk.product.vo.PromotionProductVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 秒杀活动表 前端控制器
 * </p>
 *
 * @author Jet
 * @since 2022-10-11
 */
@RestController
@RequestMapping("/promotion-seckill")
@Api(tags = "秒杀模块")
@Slf4j
public class PromotionSeckillController {

    @Autowired
    private IPromotionSeckillService promotionSeckillService;

    /**
     * 秒杀活动列表
     */
    @GetMapping
    @ApiOperation("秒杀活动列表")
    public Result findPromotionSeckill(){
        List<PromotionProductVo> list =
                promotionSeckillService.findPromotionSeckill();
        return Result.ok(list);
    }

    /**
     * 生成订单
     * 请求参数：秒杀活动id
     * 返回数据：用户id、订单编号  [定义PromotionOrderVo]
     */
    @PostMapping("/auth/order/{promotionId}")
    @ApiOperation("秒杀活动下单")
    public Result submitOrder(
            @PathVariable("promotionId") Integer promotionId,
            HttpServletRequest request) {
        log.info("秒杀生成订单！");

        // 获取登陆用户id
        String userId = request.getHeader("userId");

        // 调用service生成订单，返回vo
        PromotionOrderVo vo =
                promotionSeckillService.submitOrder(userId,promotionId);

        return Result.ok(vo);
    }

    /**
     * 确认订单
     */
    @PostMapping("/auth/order/confirm")
    @ApiOperation("确认订单")
    public Result confirmOrder(@RequestBody OrderPayDto orderPayDto,HttpServletRequest request){
        String userId = request.getHeader("userId");
        //将订单待支付的信息，存储到MQ中。
        try {
            PaymentVo vo = promotionSeckillService.confirmOrder(orderPayDto,userId);
            //返回待支付的订单数据。
            return Result.ok(vo);
        } catch (BusinessException e) {
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 订单支付
     */
    @PutMapping("/auth/pay")
    @ApiOperation("订单支付")
    public Result pay(@RequestBody OrderPayDto orderDto){
        Integer status = promotionSeckillService.payOrder(orderDto);
        return Result.ok(status);
    }
}

